package com.pi.core;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

public class Mp3Util {
    //设置APPID/AK/SK
    public static final String APP_ID = "42111933";
    public static final String API_KEY = "464783qVGyfYZ8WuriFzb0ur";
    public static final String SECRET_KEY = "ICo86j4w4pxmjo1N7Vdl1E6ZIESxo1wk";

    public static int index;

    public static String speak(String text) {
        // 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();
        // 语速，取值0-9，默认为5中语速
        options.put("spd", "5");
        // 音调，取值0-9，默认为5中语调
        options.put("pit", "5");
        // 语音风格
        options.put("per", "5003");
        TtsResponse res = client.synthesis(text, "zh", 1, options);
        byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        String mp3 = null;
        if (data != null) {
            try {
                mp3 = "output" + (index++) + ".mp3";
                Util.writeBytesToFileSystem(data, mp3);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (res1 != null) {
            System.out.println(res1.toString(2));
        }
        return mp3;
    }

    public static void main(String[] args) {
        String mp3 = Mp3Util.speak("蒋明哲同学，恭喜您老签到成功，一定要好好学习，天天向上哦！");

    }
}